<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          node-key="id"
          @current-change="selectNode"
        />
        <!--  highlight-current 等同于 :highlight-current="true" -->
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="add" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button
            v-permission="'import'"
            size="mini"
            @click="showExcelDialog = true"
          >excel导入</el-button>
          <import-excel
            :show-excel-dialog.sync="showExcelDialog"
            @uploadSuccess="getEmployList"
          />
          <el-button v-permission="'export'" size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table v-loading="loading" :data="list">
          <el-table-column label="头像" width="80px">
            <!-- !!把类型转化成布尔值 -->
            <template #default="{ row }">
              <img
                v-if="!!row.staffPhoto"
                class="avatar"
                :src="row.staffPhoto"
                alt=""
              >
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <!-- 聘用形式的处理 -->
            <template v-slot:default="{ row }">
              <span v-if="row.formOfEmployment === 1">正式工</span>
              <span v-else-if="row.formOfEmployment === 2">外包</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">详情</el-button>
              <el-button type="text" size="mini" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm title="确定删除该用户吗" @onConfirm="delEmployee(row.id)">
                <template #reference>
                  <el-button style="margin-left: 10px;" type="text" size="mini">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev,pager,next"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <!-- 弹层内容 -->
      <!-- checkbox -->
      <el-checkbox-group v-model="roleIds">
        <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
        <el-checkbox
          v-for="item in roleList"
          :key="item.id"
          :label="item.id"
        >{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row type="flex" justify="center" style="height: 80px;" align="middle">
        <el-button size="mini" type="primary" @click="btnRoleOK">确定</el-button>
        <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { exportEmployeeAPI, getDepartMentAPI, getEmployeeListAPI, delEmployeeAPI, getAllRoleEnableAPI, getEmployeeDetailAPI, assignRoleAPI } from '@/api'
import { transListToTreeData } from '@/utils'
import FileSaver from 'file-saver'
import { ImportExcel } from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [], // 树形数据
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      queryParams: {
        page: 1, // 当前页码
        pagesize: 10,
        departmentId: null,
        keyword: '' // 模糊搜索字段
      },
      total: 0, // 总数
      list: [], // 员工列表数据
      loading: false, // 加载进度管理变量
      timer: 0,
      // 控制excel的弹层显示和隐藏
      showExcelDialog: false,
      showRoleDialog: false, // 用来控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: [], // 用来双向绑定数据的
      currentUserId: null // 用来记录当前点击的用户id
    }
  },
  created() {
    this.getDepartMent()
  },
  methods: {
    async getDepartMent() {
      this.depts = transListToTreeData(await getDepartMentAPI(), 0) // 数据驱动视图
      this.queryParams.departmentId = this.depts[0].id // 记录第一个节点的id
      this.getEmployList() // 获取员工列表数据
      // 渲染是异步的！！！！
      this.$nextTick(() => {
        // 会等到上一次渲染完成
        this.$refs.deptTree.setCurrentNode(this.depts[0]) // 自动选中首个节点
      })
    },
    // 点击节点的时候记录点击的id
    selectNode(data) {
      this.queryParams.departmentId = data.id // 因为后续要根据id查询对应的数据
      this.queryParams.page = 1 // 切换了组织 要重新请求第一页数据
      this.getEmployList() // 重新加载数据
    },
    // 加载员工列表方法
    async getEmployList() {
      this.loading = true
      const { rows, total } = await getEmployeeListAPI(this.queryParams)
      this.list = rows
      console.log(this.list)

      this.loading = false
      this.total = total
    },
    // 切换页码
    changePage(newPage) {
      this.queryParams.page = newPage // 赋值新页码
      this.getEmployList() // 查询数据
    },
    // 值改变查询数据
    changeValue() {
      // 单位时间内只执行最后一次
      // this的实例上复制了一个timer的属性
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployList()
      }, 300)
    },
    async exportEmployee() {
      // 导出所有的员工接口
      const result = await exportEmployeeAPI()
      console.log(result)
      FileSaver.saveAs(result, '员工信息表.xlsx')
    },
    // 删除方法
    async delEmployee(id) {
      await delEmployeeAPI(id)
      if (this.list.length === 1) return this.queryParams.page--
      this.getEmployList()
    },
    // 获取角色列表
    async btnRole(id) {
      this.currentUserId = id
      this.roleList = await getAllRoleEnableAPI() // 获取所有可用角色
      console.log(this.roleList)
      const { roleIds } = await getEmployeeDetailAPI(id)
      this.roleIds = roleIds
      console.log(roleIds)
      this.showRoleDialog = true // 弹出层
    },
    // 点击确定时要调用分配的角色
    async btnRoleOK() {
      console.log('Selected role IDs:', this.roleIds) // 确认选中的角色ID
      console.log('Current user ID:', this.currentUserId) // 确认当前用户ID
      await this.$nextTick() // 等待DOM更新
      // 给谁分配什么样的角色
      await assignRoleAPI({
        roleIds: this.roleIds,
        id: this.currentUserId
      })
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
    .avatar {
      height: 30px;
      width: 30px;
      border-radius: 50%;
    }
  }
}
</style>
